/**
 * 角色管理页面
 */
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Select,
  Modal,
  Form,
  Tag,
  Switch,
  Popconfirm,
  Row,
  Col,
  Tooltip,
  Tree,
  Divider,
  Typography,
  Badge,
  Avatar
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  TeamOutlined,
  KeyOutlined,
  UserOutlined,
  SettingOutlined,
  CheckCircleOutlined,
  StopOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { Role, RoleCreate, RoleUpdate, Permission } from '../types/auth';
import { useAuth } from '../contexts/AuthContext';
import { showNotification } from '../utils/notification';
import api from '../services/api';
// import PerformanceMonitor from '../components/PerformanceMonitor';
import { requestGuard } from '../utils/requestGuard';

const { Search } = Input;
const { Option } = Select;
const { Title, Text } = Typography;

interface RoleManagementProps {}

const RoleManagement: React.FC<RoleManagementProps> = () => {
  // 状态管理
  const [roles, setRoles] = useState<Role[]>([]);
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedStatus, setSelectedStatus] = useState<boolean | undefined>(undefined);
  
  // 分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 模态框状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isPermissionModalVisible, setIsPermissionModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [form] = Form.useForm();

  // 权限相关状态
  const [selectedPermissions, setSelectedPermissions] = useState<number[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);

  // 防止重复请求的ref
  const isLoadingRolesRef = useRef(false);
  const isLoadingPermissionsRef = useRef(false);
  const permissionsLoadedRef = useRef(false);
  const searchTimeoutRef = useRef<NodeJS.Timeout>();

  // 权限检查 - 使用useMemo优化
  const { hasPermission } = useAuth();
  const rolePermissions = useMemo(() => ({
    canViewRoles: hasPermission('role.view'),
    canCreateRoles: hasPermission('role.create'),
    canUpdateRoles: hasPermission('role.update'),
    canDeleteRoles: hasPermission('role.delete'),
  }), [hasPermission]);

  /**
   * 获取角色列表 - 使用requestGuard防止重复请求
   */
  const fetchRoles = useCallback(async () => {
    // 直接读取当前状态值
    const currentParams = {
      page: pagination.current,
      page_size: pagination.pageSize,
      search: searchText || undefined,
      is_active: selectedStatus,
    };

    // 使用requestGuard防止重复请求
    if (!requestGuard.canRequest('fetchRoles-list', currentParams)) {
      return;
    }

    setLoading(true);

    try {

      const response = await api.get('/v1/roles', { params: currentParams });
      const data = response.data.data;

      setRoles(data.roles);
      setPagination(prev => ({
        ...prev,
        total: data.total,
      }));
    } catch (error: any) {
      showNotification('error', '获取角色列表失败', error.message);
    } finally {
      requestGuard.completeRequest('fetchRoles-list');
      setLoading(false);
    }
  }, [pagination.current, pagination.pageSize, searchText, selectedStatus]); // 添加所有依赖项

  /**
   * 获取权限列表 - 使用requestGuard防止重复请求
   */
  const fetchPermissions = useCallback(async () => {
    // 如果已经加载过，直接返回
    if (permissionsLoadedRef.current) {

      return;
    }

    // 使用requestGuard防止重复请求
    if (!requestGuard.canRequest('fetchPermissions')) {
      return;
    }

    try {

      const response = await api.get('/v1/permissions');
      setPermissions(response.data.data.permissions);
      permissionsLoadedRef.current = true;
    } catch (error: any) {
      console.error('获取权限列表失败:', error);
      showNotification('error', '获取权限列表失败', error.message);
    } finally {
      requestGuard.completeRequest('fetchPermissions');
    }
  }, []);

  // 触发数据获取的内部函数
  const triggerRolesFetch = useCallback(() => {
    fetchRoles();
  }, [fetchRoles]);

  // 初始化数据获取 - 只在组件挂载时执行一次
  useEffect(() => {
    if (!rolePermissions.canViewRoles) return;



    // 清除可能存在的请求防护状态（页面刷新时）
    requestGuard.clearGuard('fetchRoles');
    requestGuard.clearGuard('fetchPermissions');

    // 获取权限数据（只获取一次）
    if (!permissionsLoadedRef.current && !isLoadingPermissionsRef.current) {
      fetchPermissions();
    }

    // 获取角色数据
    triggerRolesFetch();
  }, [rolePermissions.canViewRoles]); // 移除函数依赖，避免无限循环

  // 分页和搜索条件变化时获取角色数据
  useEffect(() => {
    if (!rolePermissions.canViewRoles) return;


    fetchRoles();
  }, [rolePermissions.canViewRoles, fetchRoles]);

  // 搜索和筛选条件变化时的处理 - 使用防抖
  useEffect(() => {
    if (!rolePermissions.canViewRoles) return;



    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }

    searchTimeoutRef.current = setTimeout(() => {

      // 重置到第一页
      setPagination(prev => ({ ...prev, current: 1 }));
      // 注意：不在这里直接调用fetchRoles，让分页useEffect处理
    }, 300);

    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, [rolePermissions.canViewRoles, searchText, selectedStatus]);

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, []);



  /**
   * 处理搜索 - 直接触发搜索并重置分页
   */
  const handleSearch = useCallback((value: string) => {

    setSearchText(value);
    // 重置到第一页
    setPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  /**
   * 处理表格变化 - 使用useCallback优化
   */
  const handleTableChange = useCallback((paginationConfig: any) => {
    setPagination(prev => ({
      ...prev,
      current: paginationConfig.current,
      pageSize: paginationConfig.pageSize,
    }));
  }, []);

  /**
   * 打开创建/编辑模态框
   */
  const openModal = (role?: Role) => {
    setEditingRole(role || null);
    setIsModalVisible(true);
    
    if (role) {
      form.setFieldsValue({
        name: role.name,
        display_name: role.display_name,
        description: role.description,
        is_active: role.is_active,
      });
      setSelectedPermissions(role.permissions.map(p => p.id));
    } else {
      form.resetFields();
      setSelectedPermissions([]);
    }
  };

  /**
   * 关闭模态框
   */
  const closeModal = () => {
    setIsModalVisible(false);
    setEditingRole(null);
    form.resetFields();
    setSelectedPermissions([]);
  };

  /**
   * 提交表单
   */
  const handleSubmit = async (values: any) => {
    try {
      if (editingRole) {
        // 更新角色
        const updateData: RoleUpdate = {
          display_name: values.display_name,
          description: values.description,
          is_active: values.is_active,
          permission_ids: selectedPermissions,
        };
        
        await api.put(`/v1/roles/${editingRole.id}`, updateData);
        showNotification('success', '角色更新成功');
      } else {
        // 创建角色
        const createData: RoleCreate = {
          name: values.name,
          display_name: values.display_name,
          description: values.description,
          permission_ids: selectedPermissions,
        };

        await api.post('/v1/roles', createData);
        showNotification('success', '角色创建成功');
      }
      
      closeModal();
      fetchRoles();
    } catch (error: any) {
      showNotification('error', editingRole ? '角色更新失败' : '角色创建失败', error.message);
    }
  };

  /**
   * 删除角色
   */
  const handleDelete = async (roleId: number) => {
    try {
      await api.delete(`/v1/roles/${roleId}`);
      showNotification('success', '角色删除成功');
      fetchRoles();
    } catch (error: any) {
      showNotification('error', '角色删除失败', error.message);
    }
  };

  /**
   * 切换角色状态
   */
  const handleToggleStatus = async (roleId: number, isActive: boolean) => {
    try {
      await api.put(`/v1/roles/${roleId}`, { is_active: isActive });
      showNotification('success', `角色${isActive ? '启用' : '禁用'}成功`);
      fetchRoles();
    } catch (error: any) {
      showNotification('error', `角色${isActive ? '启用' : '禁用'}失败`, error.message);
    }
  };

  /**
   * 打开权限分配模态框
   */
  const openPermissionModal = (role: Role) => {
    setEditingRole(role);
    setSelectedPermissions(role.permissions.map(p => p.id));
    setCheckedKeys(role.permissions.map(p => p.id.toString()));
    setIsPermissionModalVisible(true);
  };

  /**
   * 关闭权限分配模态框
   */
  const closePermissionModal = () => {
    setIsPermissionModalVisible(false);
    setEditingRole(null);
    setSelectedPermissions([]);
    setCheckedKeys([]);
  };

  /**
   * 保存权限分配
   */
  const handleSavePermissions = async () => {
    if (!editingRole) return;
    
    try {
      await api.put(`/v1/roles/${editingRole.id}`, {
        permission_ids: selectedPermissions,
      });
      showNotification('success', '权限分配成功');
      closePermissionModal();
      fetchRoles();
    } catch (error: any) {
      showNotification('error', '权限分配失败', error.message);
    }
  };

  /**
   * 构建权限树数据
   */
  const buildPermissionTree = () => {
    const resourceMap = new Map<string, Permission[]>();

    permissions.forEach(permission => {
      if (!resourceMap.has(permission.resource)) {
        resourceMap.set(permission.resource, []);
      }
      resourceMap.get(permission.resource)!.push(permission);
    });

    return Array.from(resourceMap.entries()).map(([resource, perms]) => ({
      title: resource,
      key: resource,
      children: perms.map(perm => ({
        title: `${perm.display_name} (${perm.action})`,
        key: perm.id.toString(),
        isLeaf: true,
      })),
    }));
  };

  /**
   * 处理权限树选择
   */
  const handlePermissionCheck = (checkedKeysValue: any, info: any) => {
    const { checked, halfChecked } = info;
    setCheckedKeys(checkedKeysValue);

    // 只保留叶子节点（权限ID）
    const permissionIds = checkedKeysValue
      .filter((key: string) => !isNaN(Number(key)))
      .map((key: string) => Number(key));

    setSelectedPermissions(permissionIds);
  };

  // 表格列定义
  const columns: ColumnsType<Role> = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      render: (text: string, record: Role) => (
        <Space>
          <Avatar size="small" icon={<TeamOutlined />} />
          <div>
            <div style={{ fontWeight: 500 }}>{record.display_name}</div>
            <Text type="secondary" style={{ fontSize: '12px' }}>{text}</Text>
          </div>
        </Space>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      render: (text: string) => text || '-',
    },
    {
      title: '权限数量',
      key: 'permissions',
      width: 100,
      render: (_, record: Role) => (
        <Badge count={record.permissions.length} showZero color="#1890ff" />
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 100,
      render: (isActive: boolean, record: Role) => (
        <Switch
          checked={isActive}
          disabled={record.is_system || !rolePermissions.canUpdateRoles}
          onChange={(checked) => handleToggleStatus(record.id, checked)}
          checkedChildren={<CheckCircleOutlined />}
          unCheckedChildren={<StopOutlined />}
        />
      ),
    },
    {
      title: '类型',
      dataIndex: 'is_system',
      key: 'is_system',
      width: 80,
      render: (isSystem: boolean) => (
        <Tag color={isSystem ? 'red' : 'blue'}>
          {isSystem ? '系统' : '自定义'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record: Role) => (
        <Space size="small">
          <Tooltip title="分配权限">
            <Button
              type="text"
              icon={<KeyOutlined />}
              onClick={() => openPermissionModal(record)}
              disabled={!rolePermissions.canUpdateRoles}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => openModal(record)}
              disabled={record.is_system || !rolePermissions.canUpdateRoles}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              title="确定要删除这个角色吗？"
              description="删除后无法恢复，请谨慎操作。"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
              disabled={record.is_system || !rolePermissions.canDeleteRoles}
            >
              <Button
                type="text"
                danger
                icon={<DeleteOutlined />}
                disabled={record.is_system || !rolePermissions.canDeleteRoles}
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 权限不足提示
  if (!rolePermissions.canViewRoles) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <h3>权限不足</h3>
          <p>您没有查看角色的权限</p>
        </div>
      </Card>
    );
  }

  return (
      <div>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Row justify="space-between" align="middle">
            <Col>
              <Title level={4} style={{ margin: 0 }}>
                <TeamOutlined style={{ marginRight: 8 }} />
                角色管理
              </Title>
            </Col>
            <Col>
              <Space>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => openModal()}
                  disabled={!rolePermissions.canCreateRoles}
                >
                  新建角色
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={fetchRoles}
                  loading={loading}
                >
                  刷新
                </Button>
              </Space>
            </Col>
          </Row>
        </div>

        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          <Col xs={24} sm={12} md={8}>
            <Search
              placeholder="搜索角色名称或描述"
              allowClear
              onSearch={handleSearch}
              style={{ width: '100%' }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Select
              placeholder="选择状态"
              allowClear
              value={selectedStatus}
              onChange={setSelectedStatus}
              style={{ width: '100%' }}
            >
              <Option value={true}>启用</Option>
              <Option value={false}>禁用</Option>
            </Select>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={roles}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
          onChange={handleTableChange}
          scroll={{ x: 'max-content' }}
        />
      </Card>

      {/* 创建/编辑角色模态框 */}
      <Modal
        title={editingRole ? '编辑角色' : '新建角色'}
        open={isModalVisible}
        onCancel={closeModal}
        footer={null}
        width={600}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{ is_active: true }}
        >
          <Form.Item
            name="name"
            label="角色名称"
            rules={[
              { required: true, message: '请输入角色名称' },
              { min: 2, max: 50, message: '角色名称长度为2-50个字符' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '角色名称只能包含字母、数字和下划线' },
            ]}
          >
            <Input
              placeholder="请输入角色名称（英文标识）"
              disabled={!!editingRole}
            />
          </Form.Item>

          <Form.Item
            name="display_name"
            label="显示名称"
            rules={[
              { required: true, message: '请输入显示名称' },
              { min: 2, max: 100, message: '显示名称长度为2-100个字符' },
            ]}
          >
            <Input placeholder="请输入显示名称（中文名称）" />
          </Form.Item>

          <Form.Item
            name="description"
            label="角色描述"
          >
            <Input.TextArea
              placeholder="请输入角色描述"
              rows={3}
              maxLength={500}
              showCount
            />
          </Form.Item>

          {editingRole && (
            <Form.Item
              name="is_active"
              label="状态"
              valuePropName="checked"
            >
              <Switch
                checkedChildren="启用"
                unCheckedChildren="禁用"
                disabled={editingRole?.is_system}
              />
            </Form.Item>
          )}

          <Divider />

          <div style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={closeModal}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingRole ? '更新' : '创建'}
              </Button>
            </Space>
          </div>
        </Form>
      </Modal>

      {/* 权限分配模态框 */}
      <Modal
        title={
          <Space>
            <KeyOutlined />
            为角色 "{editingRole?.display_name}" 分配权限
          </Space>
        }
        open={isPermissionModalVisible}
        onCancel={closePermissionModal}
        width={800}
        footer={
          <div style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={closePermissionModal}>
                取消
              </Button>
              <Button type="primary" onClick={handleSavePermissions}>
                保存权限
              </Button>
            </Space>
          </div>
        }
        destroyOnClose
      >
        <div style={{ marginBottom: 16 }}>
          <Text type="secondary">
            已选择 {selectedPermissions.length} 个权限
          </Text>
        </div>

        <Tree
          checkable
          checkedKeys={checkedKeys}
          expandedKeys={expandedKeys}
          onExpand={setExpandedKeys}
          onCheck={handlePermissionCheck}
          treeData={buildPermissionTree()}
          height={400}
          style={{
            border: '1px solid #d9d9d9',
            borderRadius: 6,
            padding: 8,
          }}
        />

        <div style={{ marginTop: 16 }}>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            提示：选择资源类型将自动选择该类型下的所有权限
          </Text>
        </div>
      </Modal>
      </div>
  );
};

export default RoleManagement;
